import {
  getShopDetail,
  tempProductDetailByApp,
  twinsProductDetailByApp,
  providerProductDetailByApp
} from '@/api/shopDetail'
import { addShopCar } from '@/api/shopCar'
export default {
  data() {
    return {
      // 规格详情
      speciPopup: {
        show: false,
        purchaseNum: 1, // 购买数量
        minOrderNum: 1, // 最小起订量
        orderLimitType: '', // 步进器步长
        details: {},
        skuInfo: [],
        isNotSale: false, // 该区域是否销售此商品(false销售，true销售)
        productType: ''
      },
    }
  },
  methods: {
    // 获取查询详情接口请求
    getProductDetailsService(productType) {
      const serviceMaps = {
        1: getShopDetail, // 正常商品
        2: tempProductDetailByApp, // 临采商品
        3: twinsProductDetailByApp, // 供货商商品
        4: providerProductDetailByApp, // 一物多码商品
        6: tempProductDetailByApp // 临采商品-潜在
      }
      const requestFn = serviceMaps[productType] ?? getShopDetail
      return requestFn
    },
    // 添加购物车
    handleAddShopping(productInfo) {
      this.speciPopup.productType = productInfo?.productType
      this.getProductDetails(productInfo?.spuCode, productInfo?.productType)
      this.speciPopup.show = true
    },
    // 加入购物车
    async addPurchaseOrder() {
      if (this.speciPopup.isNotSale) return
      const { memberId: member_id } = this.vuex_accountInfo
      const { warehouseCode: warehouseId, cityCode: cityId } = this.vuex_cityInfo
      const { skuId, skuCode } = this.speciPopup.details
      if (this.speciPopup.details.priceAccuracyTag == 0) {
        this.$u.toast('该商品价格仅供参考，如需购买，请先询价');
        return
      }
      const skuIdNumlist = [{ skuId, skuCode, skuNum: this.speciPopup.purchaseNum }]
      // source - android=>10;ios=>20;wap=>30;pc=>40
      const data = { member_id, cityId, warehouseId, source: '40', skuIdNumlist }
      const res = await addShopCar(data)
      if (res.code == 0) {
        res?.errorMessage && this.$u.toast(res.errorMessage)
        // this.getCartQuantity(res.errorMessage)
      } else {
        this.$u.toast(res.errorMessage)
      }
    },
    // 立即购买
    async purchaseNow() {
      if (this.speciPopup.isNotSale) return
      const { skuCode, disPrice, spuCode } = this.speciPopup.details
      const { onActivityId } = this.speciPopup.details?.skuActivityInfo ?? {}
      const skuList = [
        {
          skuCode,
          buyyerCount: this.speciPopup.purchaseNum,
          salePrice: disPrice,
          joinPromotionTag: '10',
          activityId: onActivityId
        }
      ]
      const opsObj = {
        itemId: '',
        opsRequestMisc: '',
        requestId: '',
        spuCode
      }
      uni.navigateTo({
        url: `/ycPayments/confirmOrders/index?skuList=${encodeURIComponent(JSON.stringify(skuList))}&opsObj=${encodeURIComponent(JSON.stringify(opsObj))}`
      })
    },
    // 规格选择变更
    changeSpecSelect(specDetails) {
      this.speciPopup.details = specDetails
      this.calcPreDeliverDay() // 重新计算预计出货日
    },
    // 计算预计出货天数
    calcPreDeliverDay() {
      const { actualStock, arrivalCycle } = this.detailInfo?.skuStockInfo ?? {}
      const arrivalDay = this.speciPopup.purchaseNum > actualStock ? Number(arrivalCycle) + 1 : 1 // 如果输入的数量大于库存数，预计出货日自动加一。反之不变
      if (arrivalDay > 10 && arrivalDay <= 30) {
        this.detailInfo.arrivalCycle = 10
      } else if (arrivalDay >= 30) {
        this.detailInfo.arrivalCycle = 30
      } else {
        this.detailInfo.arrivalCycle = arrivalDay
      }
    },
    // 获取商品详情
    async getProductDetails(spuCode, productType) {
      // 初始弹窗内容
      this.speciPopup.details = {}
      this.speciPopup.skuInfo = []
      this.speciPopup.purchaseNum = 1
      this.speciPopup.minOrderNum = 1
      const IS_TEMP_PRODUCT = 2 // 临采商品
      const IS_TEMP_PRODUCT6 = 6 // 临采商品
      if (productType == IS_TEMP_PRODUCT || productType == IS_TEMP_PRODUCT6) {
        spuCode = spuCode.replace('SPU', '')
      }
      const { warehouseCode, cityCode } = this.vuex_cityInfo
      const data = {
        spuCode,
        skuCode: spuCode,
        warehouseId: warehouseCode,
        cityCode
      }
      const getDetailsServiceFn = this.getProductDetailsService(productType)
      const res = await getDetailsServiceFn(data)
      if (!res || res.code !== '0') return
      this.setSpeciPopupData(res?.skuInfos ?? [], productType)
    },
    // 设置选择规格数据
    setSpeciPopupData(skuInfo, productType) {
      const isTempGoods = productType == 2 || this.productType == 6 // 临采商品分为 线索 潜在
      this.speciPopup.isNotSale = !isTempGoods && skuInfo.some(item => item.isAvailableSales == 0) // 如果为0，则该区域不售卖该商品
      const ycSaleSkus = isTempGoods ? skuInfo : skuInfo.filter(item => item.ycSalesStauts == 1) // 筛选售卖的规格sku
      if (ycSaleSkus.length == 0) {
        this.speciPopup.isNotSale = true
        return this.$u.toast('该商品此区域暂不支持销售，非常抱歉！');
      }
      const skuDetails = this.getNewSkuInfo(ycSaleSkus)
      const { ycMiniOrder, orderLimitType } = skuDetails[0]
      this.speciPopup.purchaseNum = Number(ycMiniOrder)
      this.speciPopup.minOrderNum = Number(ycMiniOrder)
      this.speciPopup.orderLimitType = orderLimitType
      this.speciPopup.details = skuDetails[0]
      this.speciPopup.skuInfo = skuDetails
    },
    // 获取逻辑处理后的商品信息
    getNewSkuInfo(filterSku) {
      const newSkuInfo = filterSku.map((item) => { // 规格信息部分数据处理
        item.appDetail = item.appDetail ? item.appDetail.replace(/\<img/gi, '<img class="richImg"') : item.appDetail; // 替换详情数据
        item.revenueRate = (item.revenueRate == 0 || !item.revenueRate) ? 0.13 : item.revenueRate // 税率
        const { activityType, activityItemLimitNum, activityPlatform, isActivityBegin, activityPrice, activityFullStr } = item?.skuActivityInfo ?? {}
        const { skuPriceInfo: { costPrice, salePrice, retailPrice }, unitName } = item
        const { accountType } = this.vuex_memberInfo
        if (accountType !== 20) { // 如果不是签约会员
          if (!!activityPlatform && (activityPlatform.indexOf('10') >= 0 || activityPlatform.indexOf('40')  >= 0 ) && !!isActivityBegin && isActivityBegin !== 1) {
            item.activityFlag = true //自定义当前有没有活动
            if (activityPrice < costPrice) { //当活动价小于成本价，直接使用成本价
              item.disPrice = costPrice // disPrice 显示的价格
              item.delPrice = '' // delPrice 划线价，有活动显示售价
              item.conutPrice = costPrice
            } else { // 反之直接使用活动价
              item.conutPrice = activityPrice;
              item.disPrice = activityPrice
              item.delPrice = salePrice
            }
          } else { // 没有活动价直接使用售价
            item.activityFlag = false
            item.conutPrice = salePrice;
            item.disPrice = salePrice // 没有活动，直接显示售价
            if (salePrice < retailPrice) {
              item.delPrice = ''
            }
          }
        } else { // 签约会员价格显示
          item.disPrice = salePrice // disPrice 显示的价格
          item.delPrice = retailPrice // delPrice 划线价，有活动显示售价
          if (salePrice < retailPrice) {
            item.delPrice = ''
          }
          item.conutPrice = salePrice
        }
        item.noTaxPrice = (item.conutPrice / (1 + Number(item.revenueRate))).toFixed(2); // 未税价计算
        if (activityType == 10) {
          if (activityItemLimitNum == 1) {
            item.couponTips = `前1${unitName}享受活动价,超出数量以原价计算!`
          } else if (activityItemLimitNum == 0) {
            item.couponTips = '活动期间，享受活动价，不限量'
          } else {
            item.couponTips = `前1-${activityItemLimitNum}/${unitName}享受活动价,超出数量以原价计算!`
          }
        } else if (activityType == 20) {
          if (activityFullStr) {
            item.couponTips = activityFullStr
          } else {
            item.couponTips = ''
          }
        }
        return item
      })
      return newSkuInfo
    }
  }
}
